package cn.tedu.charging.device.rabbit;

import cn.tedu.charging.device.service.DeviceService;
import cn.tedu.common.pojo.constants.RabbitConstants;
import cn.tedu.common.pojo.param.GunStatusUpdateParam;
import cn.tedu.common.pojo.po.DeviceMQPO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitConsumer {


    @Autowired
    private DeviceService deviceService;
/*
    @Autowired
    private GunMapper gunMapper;*/

    @RabbitListener(queues = RabbitConstants.DEVICE_QUEUE_NAME)
    public void receive(DeviceMQPO deviceMQPO, Message message, Channel channel){
        log.debug("接收到消息：" + deviceMQPO);
        GunStatusUpdateParam gunStatusUpdateParam = new GunStatusUpdateParam();
        gunStatusUpdateParam.setGunId(deviceMQPO.getGunId());
        gunStatusUpdateParam.setStatus(deviceMQPO.getStatus());
        log.debug("更新枪的状态:{}",gunStatusUpdateParam);
        //故意抛出一个异常 模拟 消费者消费消息的时候 更新数据库 因为数据库故障 更新失败
        //throw new RuntimeException("故意抛出一个异常");

        try{
            Integer abc = null;
            //byte b = abc.byteValue(); // java.lang.NullPointerException 空指针异常 NPE
            deviceService.updateGunStatus(gunStatusUpdateParam);
            log.debug("更新枪的状态成功:{}",gunStatusUpdateParam);
            //更新成功 ack 告诉RabbitMQ 消息已经消费完毕 可以删除消息
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            try{
                channel.basicAck(deliveryTag,false);
            }catch (Exception e){
                log.error("确认消息失败",e);
            }
        }catch (Exception e){
            //更新失败 不ack 不告诉RabbitMQ 消息已经消费完毕 RabbitMQ不会删除
            log.error("更新数据库失败",e);
        }

        /*GunInfoPO gunInfoPO = new GunInfoPO();
        //set gun_status = gunStatusUpdateParam.getStatus()
        gunInfoPO.setGunStatus(deviceMQPO.getStatus());

        UpdateWrapper updateWrapper = new UpdateWrapper();
        // where id = gunStatusUpdateParam.getGunId()
        updateWrapper.eq("id",deviceMQPO.getGunId());

        //update xxx set gun_status = gunStatusUpdateParam.getStatus()  where id = gunStatusUpdateParam.getGunId()
        gunMapper.update(gunInfoPO,updateWrapper);*/
    }
}
